package com.atguigu.util;

import com.atguigu.bean.TransientSink;
import com.atguigu.common.GmallConfig;
import lombok.SneakyThrows;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author hjy
 * @create 2023/3/24 16:06
 */
public class ClickHouseUtil_hjy {
    public static <T> SinkFunction<T> getClickHouseSink(String sql) {
        return JdbcSink.sink(sql,
                new JdbcStatementBuilder<T>() {
                    @SneakyThrows
                    @Override
                    public void accept(PreparedStatement preparedStatement, T t) throws SQLException {
                        /**
                         * 通过反射获取JavaBean的所有字段
                         * 如果存在一个字段是javaBean有但是clickHouse的表中没有的
                         * 需要给javaBean的这个字段加上标签（注解）
                         * 遍历字段，这里判断是否有这个注解，有则跳过这个字段
                         * 通过preparedStatement写入
                         */

                        Class<?> aClass = t.getClass();
                        Field[] Fields = aClass.getDeclaredFields();
                        int offset=0;
                        for (int i = 0; i < Fields.length; i++) {
                            Field field = Fields[i];
                            TransientSink annotation = field.getAnnotation(TransientSink.class);
                            if (annotation!=null){
                                offset++;
                                continue;
                            }
                            field.setAccessible(true);
                            Object o = field.get(t);
                            preparedStatement.setObject(i+1-offset,o);
                        }


                    }
                }, JdbcExecutionOptions.builder()
                        .withBatchIntervalMs(1000L)
                        .withBatchSize(5)
                        .build(),
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                        .withUrl(GmallConfig.CLICKHOUSE_URL)
                        .withDriverName(GmallConfig.CLICKHOUSE_DRIVER)
                        .build());
    }
}
